package com.echo.fm.admin.auto;

import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.echo.fm.admin.auto.model.Admin;
import com.echo.util.ErrorException;
import com.echo.util.JSONResult;
import com.echo.util.JsonPagingData;
import com.echo.util.PagingInfo;
import com.echo.util.ResultUtils;
import com.echo.util.SystemWebConstant;
import com.echo.util.TimeGetter;
import com.echo.util.impl.HeaderParser;
import com.echo.util.impl.MD5Util;
import com.echo.util.impl.ValidateUtils;

@Controller
public class IAdminController {
	@Autowired
	@Qualifier("adminService")
	IAdminService adminService;

	@RequestMapping(value = "/web/admin/loginPage")
	public String loginPage(HttpServletRequest request, HttpServletResponse response) {
		return "/pages/platform/login";
	}

	@RequestMapping(value = "/web/admin/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.invalidate();
		}
		return "/pages/platform/login";
	}

	@RequestMapping(value = "/web/mainPage")
	public String mainPage(HttpServletRequest request, HttpServletResponse response) {
		return "/pages/platform/main";
	}

	@RequestMapping(value = "/web/welcome")
	public String welcome(HttpServletRequest request, HttpServletResponse response) {
		return "/pages/platform/welcome2";
	}

	@RequestMapping(value = "/web/admin/login", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	Object login(@RequestParam(value = "phone", required = true) String phone,
			@RequestParam(value = "password", required = true) String password, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			phone = phone.trim();
			HttpSession session = request.getSession(false);
			if (session != null) {
				session.invalidate();
			}
			Admin admin = adminService.searchAdminUserByPhone(phone);
			password = password.trim();
			if (admin != null) {
				String enctry = MD5Util.encrypt(password);
				boolean result = adminService.checkPassword(admin.getAdminId(), enctry);
				System.out.println("result:" + result);
				if (result) {
					String token = UUID.randomUUID().toString().replaceAll("-", "");
					session = request.getSession(true);
					admin.setPassword("");
					session.setAttribute(token, admin);
					session.setMaxInactiveInterval(3600 * 2);
					HeaderParser.setToken(request, response, token);
					JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
					String msg = "你的账号是:%s,你的密码是:%s";
					jsonResult.setData(String.format(msg, phone, password));
					return jsonResult;
				} else {
					return ResultUtils.instJSONResult(ResultUtils.WEB_PASSWORD_ERROR_CODE);
				}
			} else {
				return ResultUtils.instJSONResult(ResultUtils.WEB_USERNAME_ERROR_CODE);
			}
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}
	}

	@RequestMapping(value = "/web/admin/regist")
	@ResponseBody
	Object regist(@RequestParam(value = "username", required = true) String userName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "phone", required = true) String phone, HttpServletRequest request,
			HttpServletResponse response) {
		String scret = MD5Util.encrypt(password);
		try {
			adminService.registAdmin(userName, scret, phone);
			JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			String result = "注册成功,你的用户名是%s";
			jsonResult.setData(String.format(result, userName));
			return jsonResult;
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}
	}

	@RequestMapping(value = "/web/admin/updateSave", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object updateUser(HttpServletRequest request, HttpServletResponse response) {
		try {
			String phone = request.getParameter("phone");
			Admin adminExist = adminService.searchAdminUserByPhone(phone);
			if (adminExist != null) {
				String userName = request.getParameter("userName");
				if (ValidateUtils.isNotEmpty(userName)) {
					adminExist.setUserName(userName);
				}
				String password = request.getParameter("password");
				String scret = MD5Util.encrypt(password);
				if (ValidateUtils.isNotEmpty(scret)) {
					adminExist.setPassword(scret);
				}
				adminExist.setT(TimeGetter.getTime());
			}
			adminService.updateUserById(adminExist);
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.RADIO_SERVICE_IS_STOPED);
		}
	}

	@RequestMapping(value = "/web/admin/deleteSave", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	Object deleteUser(HttpServletRequest request, HttpServletResponse response) {
		try {
			String phone = request.getParameter("phone");
			Admin admin = adminService.searchAdminUserByPhone(phone);
			if (admin != null) {
				adminService.deleteUser(admin);
			}
			return ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
		} catch (ErrorException e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}
	}

	@RequestMapping(value = "/web/admin/listSearch")
	@ResponseBody
	Object listAdmin(HttpServletRequest request, HttpServletResponse response) {

		try {
			// 根据电话查询
			String phone = null;
			String phoneStr = request.getParameter("phone");
			if (ValidateUtils.isNotEmpty(phoneStr)) {
				phone = new String(phoneStr.getBytes("ISO-8859-1"), "UTF-8");
			}
			// 根据昵称查询
			String userName = null;
			String userNameStr = request.getParameter(userName);
			if (ValidateUtils.isNotEmpty(userNameStr)) {
				userName = new String(userNameStr.getBytes("ISO-8859-1"), "UTF-8");
			}
			String page = request.getParameter("page");
			PagingInfo pagingInfo = new PagingInfo();
			int firstResult = 0;
			if (ValidateUtils.isNotEmpty(page)) {
				firstResult = (Integer.parseInt(page) - 1) * SystemWebConstant.DEFAULT_PAGE_SIZE;
				pagingInfo.setCurrentPage(Integer.parseInt(page));
			}
			List<Admin> adminList = adminService.searchAdminList(phoneStr, userNameStr,
					SystemWebConstant.DEFAULT_PAGE_SIZE, firstResult);
			JSONResult jsonResult = ResultUtils.instJSONResult(ResultUtils.WEB_SUCCESS_CODE);
			JsonPagingData jsonPagingData = new JsonPagingData();
			jsonPagingData.setPaging(pagingInfo);
			jsonPagingData.setList(adminList);
			jsonResult.setData(jsonPagingData);

			return jsonResult;
		} catch (Exception e) {
			e.printStackTrace();
			return ResultUtils.instJSONResult(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		}

	}

}
